<template>
  <t-modal
    :title="filterTitle"
    width="900px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    wrapClassName="add-modal-container"
    forceRender
    v-bind:confirmLoading="confirmLoading"
    v-bind="footer"
  >
    <div class="curve-modal-body">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="isDisabled"
      >
        <a-form-model-item
          :label="item.label"
          :prop="item.key"
          v-for="(item, index) in formList"
          :key="index"
          :rules="{
            required: item.required,
            message: item.message,
          }"
        >
          <!-- 文本框 -->
          <a-input
            :disabled="isDisabled"
            v-if="item.type == 'input'"
            v-model="form[item.key]"
            :placeholder="isDisabled ? '' : item.placeholder"
          ></a-input>
          <!-- 下拉框 -->
          <a-select
            v-else-if="item.type == 'select'"
            style="width: 100%"
            v-model="form[item.key]"
            :placeholder="isDisabled ? '' : item.placeholder"
            :filter-option="filterOption"
            show-search
            :disabled="isDisabled"
          >
            <a-select-option
              :value="v[item.select_code]"
              v-for="(v, i) in item.select_list"
              :key="i"
            >
              {{ v[item.select_name] }}
            </a-select-option>
          </a-select>
          <!-- 日期 -->
          <a-date-picker
            v-else-if="item.type == 'date'"
            style="width: 100%"
            v-model="form[item.key]"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            :disabled="isDisabled"
          />
          <!-- 文件 -->
          <bjUploadFile
            :viewMode="isDisabled"
            v-else-if="item.type == 'file'"
            :count="1"
            v-model="form[item.key]"
            @change="upLoadFileChange($event, item.key)"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @remove="removeFile($event, item.key)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
          <!-- 图片 -->
          <bjUploadImg
            :viewMode="isDisabled"
            v-else-if="item.type == 'image'"
            :count="1"
            v-model="form[item.key]"
            @change="upLoadImage($event, item.key)"
            replaceField="url"
          ></bjUploadImg>
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { downloadDfs, getToken } from "@/utils/TopVUI";
import { mapGetters } from "vuex";
//图片
import bjUploadImg from "@/components/extendCustom/bj-upload-img";
//文件
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import {
  addAchievement,
  editAchievement,
  detailAchievement,
} from "@/api/knowledgeBase";

import formMixin from "./form.js";

export default {
  components: {
    bjUploadImg,
    bjUploadFile,
    previewModal,
  },
  mixins: [formMixin],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    code: {
      type: String,
      default: "",
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    operateType: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      form: {
        //名称
        fileName: "",
        //期刊名称
        secondName: "",
        //批准文号
        fileNumber: "",
        //参与方式
        participationMethod: undefined,
        //标准类型
        standardType: undefined,
        //奖励等级
        rewardLevel: undefined,
        //批准部门
        department: "",
        //完成时间、授权时间、施行时间
        completedDate: "",
        //参编人员、完成人、作者
        completedBy: "",
        //收录数据库
        databaseInclusion: undefined,
        //公司
        companyCode: undefined,
        //项目
        proCode: undefined,
        //主文件
        files: [],
        //副文件
        secondFiles: [],
      },
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      confirmLoading: false,
    };
  },
  computed: {
    ...mapGetters(["nickname", "configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    filterTitle() {
      let { operateType } = this;
      switch (operateType) {
        case 1:
          return "新增";
        case 2:
          return "编辑";
        case 3:
          return "详情";
        default:
          break;
      }
    },
    isDisabled() {
      let { operateType } = this;
      switch (operateType) {
        case 1:
          return false;
        case 2:
          return false;
        case 3:
          return true;
        default:
          break;
      }
    },
    footer() {
      let { operateType } = this;
      switch (operateType) {
        case 1:
          return {};
        case 2:
          return {};
        case 3:
          return {
            footer: null,
          };
        default:
          break;
      }
    },
  },
  watch: {
    visible: {
      async handler(val) {
        if (val) {
          await this.initFormItems();
          let { uuid } = this.parameter;
          if (uuid) {
            await this.getDetail();
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();

      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let { url } = row;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    //详情
    getDetail() {
      let { uuid } = this.parameter;
      detailAchievement({ uuid })
        .then((res) => {
          this.form = {
            //名称
            fileName: res.fileName,
            //期刊名称
            secondName: res.secondName,
            //批准文号
            fileNumber: res.fileNumber,
            //参与方式
            participationMethod: res?.participationMethod ?? undefined,
            //标准类型
            standardType: res?.standardType ?? undefined,
            //奖励等级
            rewardLevel: res?.rewardLevel ?? undefined,
            //批准部门
            department: res.department,
            //施行日期
            completedDate: res.completedDate,
            //参编人员
            completedBy: res.completedBy,
            //收录数据库
            databaseInclusion: res?.databaseInclusion ?? undefined,
            //公司
            companyCode: res.companyCode,
            //项目
            proCode: res?.proCode ?? undefined,
            //文件
            files: JSON.parse(res?.files ?? "[]"),
            //副文件
            secondFiles: JSON.parse(res?.secondFiles ?? "[]"),
          };
        })
        .catch((_) => {});
    },
    addAchievement,
    editAchievement,
    //提交
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let { form, code, parameter } = this;
          let { files, secondFiles } = form;
          //主文件
          const fileList = files.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          //副文件
          const fileList_2 = secondFiles.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          let formJson = {
            //名称
            fileName: form.fileName,
            //期刊名称
            secondName: form.secondName,
            //批准文号
            fileNumber: form.fileNumber,
            //参与方式
            participationMethod: form.participationMethod,
            //标准类型
            standardType: form.standardType,
            //批准部门
            department: form.department,
            //完成时间、授权时间、施行时间
            completedDate: form.completedDate,
            //参编人员、完成人、作者
            completedBy: form.completedBy,
            //收录数据库
            databaseInclusion: form.databaseInclusion,
            //奖励等级
            rewardLevel: form.rewardLevel,
            //公司
            companyCode: form.companyCode,
            //项目
            proCode: form.proCode,
            //主文件
            files: JSON.stringify(fileList),
            //副文件
            secondFiles: JSON.stringify(fileList_2),
            //文件类型
            fileType: code,
          };
          let baseUrl = "addAchievement";
          //编辑
          if (parameter.uuid) {
            this.$set(formJson, "uuid", parameter.uuid);
            baseUrl = "editAchievement";
          }
          this[baseUrl](formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.$parent.getTreeData();
                this.closeModal();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    //上传图片
    upLoadImage({ file, index }, attrName) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[attrName][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form[attrName][index], "uid", res.dfsFileUuid);
          this.$set(this.form[attrName][index], "url", res.url);
          this.$set(this.form[attrName][index], "fileName", file.name);
        })
        .catch((_) => {
          this.$set(this.form[attrName][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[attrName][index], "loading", false);
        });
    },
    //删除文件
    removeFile({ file, index }, attrName) {
      if (attrName == "files") {
        this.form.fileName = "";
      }
    },
    //上传文件
    upLoadFileChange({ file, index }, attrName) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[attrName][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form[attrName][index], "uid", res.dfsFileUuid);
          this.$set(this.form[attrName][index], "url", res.url);

          if (attrName == "files") {
            let lastIdx = file.name.lastIndexOf(".");
            this.form.fileName = file.name.substring(0, lastIdx);
            this.$refs["ruleForm"].clearValidate(["fileName"]);
          }
        })
        .catch((_) => {
          if (attrName == "files") {
            this.form.fileName = "";
          }

          this.$set(this.form[attrName][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[attrName][index], "loading", false);
        });
    },
    resetForm() {
      this.formList = [];
      this.form = {
        //名称
        fileName: "",
        //期刊名称
        secondName: "",
        //批准文号
        fileNumber: "",
        //参与方式
        participationMethod: undefined,
        //标准类型
        standardType: undefined,
        //奖励等级
        rewardLevel: undefined,
        //批准部门
        department: "",
        //完成时间、授权时间、施行时间
        completedDate: "",
        //参编人员、完成人、作者
        completedBy: "",
        //收录数据库
        databaseInclusion: undefined,
        //公司
        companyCode: undefined,
        //项目
        proCode: undefined,
        //主文件
        files: [],
        //副文件
        secondFiles: [],
      };
      this.$refs.ruleForm.resetFields();
    },
    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    padding: 14px;
    box-sizing: border-box;
    max-height: 700px;
    overflow: hidden;
    overflow-y: auto;
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        flex-shrink: 0;
        width: 100px;
        white-space: pre-wrap;
        display: flex;
        justify-content: flex-end;
        line-height: 20px;
        margin-right: 2px;
        align-items: center;
        height: 36px;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        overflow: hidden;
      }
    }
    .bj-upload-file {
      .choosed-file-warp {
        width: 100%;
      }
    }
  }
}
</style>
